package work.zhengyun.demo.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @Author: zhengyun
 * @Email: 574860631@qq.com
 * @Date: 2021/3/24 0:08
 */
public class NIOChlient {
    public static void main(String[] args) throws Exception{
        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //提供服务端的ip 和端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",6666);
        //连接服务器
        if(!socketChannel.connect(inetSocketAddress)){
            while ((!socketChannel.finishConnect())){
                System.out.println("因为需要时间，客户端不会堵塞可以做其他工作");
            }
        }
        //如果连接成功，就发送数据
        String str = "hello,世界~";
        //
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        //发送数据， 将buffer 数据写入channel
        socketChannel.write(buffer);
        System.in.read();
    }
}
